//
//  EvenReviewVC.m
//  ConvenientlyTake
//
//  Created by 森鑫 on 2022/12/23.
//

#import "EvenReviewVC.h"
#import "EvenDetailBottomView.h"
#import "EventDetailAPIRequest.h"
@interface EvenReviewVC ()<TGChoosePhotoViewDelegate, QMUITextViewDelegate, QMUITextFieldDelegate,EvenDetailBottomViewBtnDelegate>
@property (weak, nonatomic) IBOutlet QMUITextView *descTextView;
@property (weak, nonatomic) IBOutlet UILabel *descNumLabel;


@property (weak, nonatomic) IBOutlet UILabel *photoNumLabel;
@property (weak, nonatomic) IBOutlet TGChoosePhotoView *choosePhotoView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *choosePhotoViewHeight;

@property (nonatomic, strong) NSArray *imgUrlInfoArray;
@property (nonatomic , strong) EvenDetailBottomView *bottomView;
@property (nonatomic , strong) UIView *contentView;

@end

@implementation EvenReviewVC


- (void)viewDidLoad {
    [super viewDidLoad];
    self.title=@"审核";
    [self setupUI];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(showKeyboard:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(hideKeyboard:) name:UIKeyboardWillHideNotification object:nil];
}

- (void)setupNavigationItems {
    [super setupNavigationItems];
    [self setNavStyleWhiteAndBackBtn];
}

- (void)setupUI {
    self.descTextView.placeholder = @"请在此输入审核意见";
    self.descTextView.placeholderColor = TextViewPlaceholderColor;
    self.descTextView.font = TGMediumAFont(15);
    self.descTextView.textColor = DeepBlackColor;
    self.descTextView.delegate = self;
    
    self.choosePhotoView.uploadImageType = UploadImageType_CONTRACT_SERVICE;
    self.choosePhotoView.maxCount = 10;
    self.choosePhotoViewHeight.constant = PhotoCollectionViewHeight(1);
    self.choosePhotoView.delegate = self;
    
    [self.view addSubview:self.bottomView];
    [self.bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.bottom.right.equalTo(self.view).offset(0);
        make.height.mas_equalTo(102);
    }];
    
}

#pragma mark bottomViewDelegate
- (void)selelctItemWitIndex:(NSInteger)index andSender:(UIButton *)sender{
    NSMutableArray *imagesList = [NSMutableArray array];
   
    if([sender.titleLabel.text isEqualToString:@"驳回"]) {
        [self alertRejectWithBlock:^(NSString *reason) {
            [self rejectActionWithReason:reason];
        }];
    }
    if ([sender.titleLabel.text isEqualToString:@"通过"]) {
        for (TGUrlInfoModel *imgInfoModel in self.imgUrlInfoArray) {
            [imagesList addObject:@{@"fileType": @"1", @"fileName": R(imgInfoModel.filename), @"filePath": R(imgInfoModel.fullPath)}];
        }
        [TGProgressHUD showHUD:nil];
        [EventDetailAPIRequest POSTWorkingAuditApprovehAuditTaskId:self.auditTaskId  disposalDesc:self.descTextView.text imagesList:imagesList success:^(TGResponseItem *responseItem) {
            [TGProgressHUD dismissMPHUD];
            if (responseItem.success) {
                [TGLEEAlert eventAlertTipImage:@"review_progress" andMessage:@"审核通过" cancel:@"返回" click:^(NSInteger index) {
                    [[NSNotificationCenter defaultCenter] postNotificationName:KNotificationWithRefresheEventDetailVC object:nil];
                    [[NSNotificationCenter defaultCenter] postNotificationName:KNotificationWithRefresheEventCenterVC object:nil];
                    [self.navigationController popViewControllerAnimated:YES];
                }];
            }
        } fail:^(NSError *error) {
            [TGProgressHUD dismissMPHUD];
        }];  
    }
}
-(void)rejectActionWithReason:(NSString *)reason{
    [TGProgressHUD showHUD:nil];
    [EventDetailAPIRequest POSTWorkingAuditRejectWithAuditTaskId:self.auditTaskId rejectionReason:reason success:^(TGResponseItem *responseItem) {
        [TGProgressHUD dismissMPHUD];
        if (responseItem.success) {
            [[NSNotificationCenter defaultCenter] postNotificationName:KNotificationWithRefresheEventDetailVC object:nil];
            [[NSNotificationCenter defaultCenter] postNotificationName:KNotificationWithRefresheEventCenterVC object:nil];
            [self.navigationController popViewControllerAnimated:YES];
        }
    } fail:^(NSError *error) {
        [TGProgressHUD dismissMPHUD];
    }];
}

#pragma mark QMUITextViewDelegate
- (void)textViewDidChange:(UITextView *)textView {
    if (textView.text.length > 200) {
        [TGProgressHUD showHUDTip:@"审核意见不能超过200个字符"];
        NSMutableAttributedString *attStr = [[NSMutableAttributedString alloc]initWithString:@"200/200"];
        [attStr addAttribute:NSForegroundColorAttributeName value:UIColorRed range:NSMakeRange(0, 3)];
        self.descNumLabel.attributedText = attStr;
        self.descTextView.text = [textView.text substringToIndex:200];
    } else {
        self.descNumLabel.text = [NSString stringWithFormat:@"%zd/200", textView.text.length];
    }
}


#pragma mark TGChoosePhotoViewDelegate
- (void)tgChoosePhotoViewDidSelectImgArray:(NSArray *)imgArray imgUrlInfoArray:(NSArray <TGUrlInfoModel *>*)imgUrlInfoArray {
    NSLog(@"++++%@,-----%@", imgArray, imgUrlInfoArray);
    self.photoNumLabel.text = [NSString stringWithFormat:@"照片(%lu/10)" , (unsigned long)imgArray.count];
    NSInteger count = ceil((imgArray.count+1)/4.0);
    self.choosePhotoViewHeight.constant = PhotoCollectionViewHeight(count);
    self.imgUrlInfoArray = imgUrlInfoArray;
}

- (EvenDetailBottomView *)bottomView{
    if(!_bottomView){
        _bottomView = [[[NSBundle mainBundle] loadNibNamed:@"EvenDetailBottomView" owner:self options:0] firstObject];
        _bottomView.delegate = self;
        [_bottomView.leftBtn setTitle:@"驳回" forState:UIControlStateNormal];
        [_bottomView.rightBtn setTitle:@"通过" forState:UIControlStateNormal];

    }
    return _bottomView;
}

- (void)alertRejectWithBlock:(void(^)(NSString *reason))block{
    LEEActionSheetConfig *alert = [LEEAlert actionsheet];
    QMUITextView *textView = [[QMUITextView alloc] initWithFrame:CGRectMake(RatioWidth(10), 48, SCREEN_WIDTH - RatioWidth(20), RatioWidth(180))];
    textView.textColor = DeepBlackColor;
    textView.font = TGAutoFont(16);
    textView.placeholder = @"请输入";
    textView.contentInset = UIEdgeInsetsMake(0, 5, 5, 5);
    textView.placeholderColor = LightGrayColor;
    textView.backgroundColor = [UIColor whiteColor];
    textView.layer.cornerRadius = TableViewCornerRadius;
    
    UIView *contentView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, RatioWidth(266))];
    self.contentView = contentView;
    UIView *topView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 28)];
    [contentView addSubview:topView];
    [contentView addSubview:textView];
    
    QMUIButton *cancelBtn = [[QMUIButton alloc] init];
    [cancelBtn setTitle:@"取消" forState:UIControlStateNormal];
    [cancelBtn setTitleColor:RGBA(134, 144, 156, 1) forState:UIControlStateNormal];
    cancelBtn.titleLabel.font = TGAutoFont(16);
    [topView addSubview:cancelBtn];
    [cancelBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(16);
        make.top.bottom.mas_equalTo(0);
    }];
    [cancelBtn addBlockForControlEvents:UIControlEventTouchUpInside block:^(id  _Nonnull sender) {
        [LEEAlert closeWithIdentifier:@"close_reject" completionBlock:^{
            
        }];
    }];
    
    QMUIButton *sureBtn = [[QMUIButton alloc] init];
    [sureBtn setTitle:@"确定" forState:UIControlStateNormal];
    [sureBtn setTitleColor:GlobalBarBlueTinColor forState:UIControlStateNormal];
    sureBtn.titleLabel.font = TGAutoFont(16);
    [topView addSubview:sureBtn];
    [sureBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(-16);
        make.top.bottom.mas_equalTo(0);
    }];
    [sureBtn addBlockForControlEvents:UIControlEventTouchUpInside block:^(id  _Nonnull sender) {
        if (textView.text.length == 0) {
            [TGProgressHUD showHUDTip:@"请输入驳回原因"];
            return;
        }
        if (block){
            block(textView.text);
        }
        [LEEAlert closeWithIdentifier:@"close_reject" completionBlock:^{
            
        }];
    }];
    
    QMUILabel *titleLabel = [[QMUILabel alloc] init];
    titleLabel.text = @"驳回原因";
    titleLabel.textColor = RGBA(29, 33, 41, 1);
    titleLabel.font = [TG_UIHelper TGAutoFount:18 name:Ping_Medium];
    [topView addSubview:titleLabel];
    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(topView.mas_centerX);
        make.centerY.mas_equalTo(topView.mas_centerY);
    }];
    
    alert.config
    .LeeMaxWidth(SCREEN_WIDTH)
//    .LeeMaxHeight(RatioWidth(300))
    .LeeStatusBarStyle(UIStatusBarStyleLightContent)
    .LeeIdentifier(@"close_reject")
    .LeeAddCustomView(^(LEECustomView *custom) {
        custom.view = contentView;
        custom.positionType = LEECustomViewPositionTypeCenter;
    })
    .LeeActionSheetBottomMargin(0.0) // 设置底部距离屏幕的边距
    .LeeActionSheetBackgroundColor([UIColor whiteColor])
    .LeeCornerRadii(CornerRadiiMake(10, 10, 0, 0))   // 指定整体圆角半径
    .LeeAvoidKeyboard(YES)
    .LeeShow();
}

-(void)showKeyboard:(NSNotification *)notification
{
    //键盘出现后的位置
    CGRect endFrame = [notification.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    CGFloat keyboardHeight = endFrame.size.height;
    //键盘弹起时的动画效果
    UIViewAnimationOptions option = [notification.userInfo[UIKeyboardAnimationCurveUserInfoKey] intValue];
    //键盘动画时长
    NSTimeInterval duration = [notification.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    __block typeof(self)weakSelf = self;
    
    [UIView animateWithDuration:duration delay:0 options:option animations:^{
        [self.contentView setFrame:CGRectMake(0, 0, SCREEN_WIDTH, RatioWidth(266) + keyboardHeight)];
    } completion:nil];
    
}
#pragma mark --- 收起键盘
-(void)hideKeyboard:(NSNotification *)notification
{
    NSLog(@"收起键盘");
    UIViewAnimationOptions option = [notification.userInfo[UIKeyboardAnimationCurveUserInfoKey] intValue];
    NSTimeInterval duration = [notification.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    __weak typeof(self)weakSelf = self;
    [UIView animateWithDuration:duration delay:0 options:option animations:^{
        [self.contentView setFrame:CGRectMake(0, 0, SCREEN_WIDTH, RatioWidth(266))];
    } completion:^(BOOL finished) {
        
    }];
}
- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end
